package org.jpass.dc.business.user.logic;

import java.sql.SQLException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.jpass.dc.business.user.bean.UserVOBean;
import org.jpass.dc.business.user.dao.UserManageDao;
import org.jpass.dc.business.user.dao.UserManageDaoImpl;
import org.jpass.dc.common.bean.Page;
import org.jpass.dc.common.exception.ApplicationException;
import org.jpass.dc.common.util.Encrypter;
import org.jpass.dc.common.util.RefParaValue;

public class UserManageLogicImpl implements UserManageLogic {
	private UserManageDao userManageDao = new UserManageDaoImpl();

	@Override
	public UserVOBean login(UserVOBean voBean) throws Exception {
		String email = voBean.getEmail();
		String password = voBean.getPassword();
		try{
			UserVOBean user = userManageDao.findUserByEmail(email);
			if (RefParaValue.empty(user)) {
				throw new ApplicationException("noUser");
			} else {
				if(user.getIsActivated()!=1){
					throw new ApplicationException("noAct");//未激活
				}
				if (password.equals(user.getPassword())) {
					int loginTimes = user.getLoginTimes();
					if(loginTimes==0){ //修改登录次数
						user.setLoginTimes(1);
					}else{
						user.setLoginTimes(loginTimes+1);
					}
					user.setPoint(user.getPoint()+2);
					user.setIsOnline(1);
					user.setThisSignTime(new Date()); //设置登录时间
					userManageDao.updateUser(user);
					return user;
				} else {
					return null;
				}
			}
		}catch(SQLException e){
			throw new ApplicationException("用户登录时发生数据库操作错误！");
		}
	}

	@Override
	public String register(UserVOBean voBean) throws Exception {
		String result = "success";
		String email = voBean.getEmail();
		String username = voBean.getUsername();
		try {
			UserVOBean user = userManageDao.findUserByEmail(email);
			if(!RefParaValue.empty(user)){
				result = "email";
				return result;
			}
			UserVOBean user1 = userManageDao.findUserByEmail(username);
			if(!RefParaValue.empty(user1)){
				result = "username";
				return result;
			}
			/*List<UserVOBean> allUserList = userManageDao.findAllUserList();
			if (allUserList != null) {
				for (int i = 0; i < allUserList.size(); i++) {
						result = "email";
						return result;
					UserVOBean user = allUserList.get(i);
					if (email.equals(user.getEmail())) { // 判断邮箱是否已注册过
						result = "email";
						return result;
					} else if (username.equals(user.getUsername())) { // 判断是否存在同名用户
						result = "username";
						return result;
					}
				}
			}*/
			if(RefParaValue.empty(voBean.getIsActivated())){
				voBean.setIsActivated(0);
			}
			userManageDao.addUser(voBean);
		} catch (SQLException e) {
			throw new ApplicationException("用户注册时发生数据库操作错误！");
		}
		return result;
	}
	
	@Override
	public boolean activate(String username, String token) throws Exception {
		boolean result = false;
		try {
			UserVOBean user = userManageDao.findUserByEmail(username);
			Calendar ca_send = Calendar.getInstance();
			Calendar ca_today = Calendar.getInstance();
			ca_send.setTime(user.getSendEmailTime());
			ca_send.add(Calendar.DATE, 1);
			ca_today.setTime(new Date());
			if(ca_send.before(ca_today)){
				throw new ApplicationException("激活链接已过期！");
			}
			
			if (token.equals(user.getToken())&& user.getIsActivated()==0) { //判断激活码
				user.setIsActivated(1);
				userManageDao.updateUser(user); //修改激活标识
				result = true;
				return result;
			}else{
				throw new ApplicationException("激活链接出错或账户已激活！");
			}
		} catch (SQLException e) {
			throw new ApplicationException("用户账户激活时发生数据库操作错误！");
		}
	}

	@Override
	public UserVOBean forgetPass(String email) throws Exception {
		UserVOBean user = null;
		try{
			user = userManageDao.findUserByEmail(email);
			if(RefParaValue.empty(user)){ //是否存在注册邮箱
				return null;
			}else{
				user.setSendForgetEmailTime(new Date());
				userManageDao.updateUser(user);
			}
		}catch (SQLException e) {
			throw new ApplicationException("发送忘记密码邮件是发生数据库操作错误！");
		}
		return user;
	}

	@Override
	public UserVOBean updatePass(String username, String password) throws Exception {
		UserVOBean user = null;
		try{
			user = userManageDao.findUserByEmail(username);
			if(!RefParaValue.empty(user)){ 
				if(RefParaValue.empty(password)){
					Calendar ca_send = Calendar.getInstance();
					Calendar ca_today = Calendar.getInstance();
					ca_send.setTime(user.getSendForgetEmailTime());
					ca_send.add(Calendar.DATE, 1);
					ca_today.setTime(new Date());
					if(ca_send.before(ca_today)){
						throw new ApplicationException("修改密码链接已过期！");
					}
				}else{
					user.setPassword(Encrypter.md5Encrypt(password));
					userManageDao.updateUser(user);
				}
				return user;
			}
		}catch (SQLException e) {
			throw new ApplicationException("修改用户密码时发生数据库操作错误！");
		}
		return null;
	}

	@Override
	public boolean updateLogoutStatus(UserVOBean user) throws Exception {
		try {
			UserVOBean userVar = userManageDao.findUserById(user.getId());
			if(RefParaValue.empty(userVar.getLastSignTime())){
				user.setLastSignTime(userVar.getCreatedDate()); //若没登录过的显示注册时间
			}else{
				user.setLastSignTime(userVar.getThisSignTime());
			}
			user.setIsOnline(0);
			userManageDao.updateUser(user);
		} catch (SQLException e) {
			throw new ApplicationException("更新用户注销状态时发生数据库操作错误！");
		}
		return true;
	}

	@Override
	public List<?> findUserList(Page page, String findUsername) throws Exception {
		List<?> list = null;
		try {
			list =  userManageDao.findBackUserList(page, findUsername);
		} catch (SQLException e) {
			throw new ApplicationException("返回所有用户列表上时发生数据库操作错误！");
		}
		return list;
	}
	
	@Override
	public UserVOBean findUserInfoById(String userId) throws Exception {
		UserVOBean user = null;
		try {
			user = userManageDao.findUserById(userId);
			if(!RefParaValue.empty(user)){
				return user;
			}else{
				throw new ApplicationException("根据ID查询用户出错，无此ID用户，如有疑问请联系管理员。");
			}
		} catch (SQLException e) {
			throw new ApplicationException("删除用户时发生数据库操作错误！");
		}
	}
	
	@Override
	public boolean deleteUser(String deleteIds) throws Exception {
		String[] deleteId = deleteIds.split("\\|");
		UserVOBean user = null;
		try {
			for(int i=0;i<deleteId.length;i++){
				user = userManageDao.findUserById(deleteId[i]);
				if(!RefParaValue.empty(user)){
					userManageDao.deleteUserObj(user);
				}else{
					throw new ApplicationException("根据ID查询用户出错，无此ID用户，如有疑问请联系管理员。");
				}
			}
		} catch (SQLException e) {
			throw new ApplicationException("删除用户时发生数据库操作错误！");
		}
		return true;
	}
	
	@Override
	public boolean updateUserInfo(UserVOBean user) throws Exception {
		try {
			UserVOBean userNew = userManageDao.findUserById(user.getId());
			if(!RefParaValue.empty(userNew)){
				userNew.setBirthday(user.getBirthday());
				userNew.setGroup(user.getGroup());
				userNew.setRealName(user.getRealName());
				userNew.setPoint(Integer.parseInt(user.getPoint().toString()));
				userNew.setSex(user.getSex());
				userNew.setNotes(user.getNotes());
				/*if("1".equals(user.getSex())){
					userNew.setSex("男");
				}else if("0".equals(user.getSex())){
					userNew.setSex("女");
				}*/
				userManageDao.updateUser(userNew);
			}
		} catch (SQLException e) {
			throw new ApplicationException("修改用户信息时发生数据库操作错误！");
		}
		return true;
	}
	
	@Override
	public boolean modifyUserInfo(UserVOBean user) throws Exception {
		try {
			UserVOBean userNew = userManageDao.findUserById(user.getId());
			if(!RefParaValue.empty(userNew)){
				userNew.setBirthday(user.getBirthday());
				userNew.setRealName(user.getRealName());
				userNew.setNotes(user.getNotes());
				if("0".equals(user.getSex())){
					userNew.setSex("女");
				} else {
					userNew.setSex("男");
				}
				userManageDao.updateUser(userNew);
			} else {
				return false;
			}
		} catch (SQLException e) {
			throw new ApplicationException("修改用户信息时发生数据库操作错误！");
		}
		return true;
	}
	
	@Override
	public boolean resetPass(String userId, String password) throws Exception {
		try {
			if(!RefParaValue.empty(userId)){
				UserVOBean user = userManageDao.findUserById(userId);
				if(!RefParaValue.empty(user)){
					user.setPassword(password);
					userManageDao.updateUser(user);
				}else{
					throw new ApplicationException("无此用户，如有疑问请联系管理员。");
				}
			}
		} catch (SQLException e) {
			throw new ApplicationException("修改用户密码时发生数据库操作错误！");
		}
		return true;
	}
}
